package org.summerframework.core.util;

import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.Assert;
import org.springframework.util.PatternMatchUtils;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author 石超
 * @version v1.0.0
 */
public class AnnotationAutoProxyCreator extends AbstractAutoProxyCreator implements InitializingBean, ApplicationContextAware {

    private static final long serialVersionUID = -9094985530784052264L;

    private List<Class<? extends Annotation>> annotations;

    private ApplicationContext context;

    private List<String> beanNames = new ArrayList<String>();

    /**
     * @param annotations annotation
     */
    public void setAnnotations(List<Class<? extends Annotation>> annotations) {
        this.annotations = annotations;
    }

    @Override
    public void setApplicationContext(ApplicationContext context) {
        this.context = context;
    }

    /**
     * Identify as bean to proxy if the bean name is in the configured list of names.
     */
    @Override
    @SuppressWarnings("rawtypes")
    protected Object[] getAdvicesAndAdvisorsForBean(Class beanClass, String beanName, TargetSource targetSource) {
        for (String mappedName : this.beanNames) {
            if (FactoryBean.class.isAssignableFrom(beanClass)) {
                if (!mappedName.startsWith(BeanFactory.FACTORY_BEAN_PREFIX)) {
                    continue;
                }
                mappedName = mappedName.substring(BeanFactory.FACTORY_BEAN_PREFIX.length());
            }
            if (isMatch(beanName, mappedName)) {
                return PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS;
            }
        }
        return DO_NOT_PROXY;
    }

    /**
     * Return if the given bean name matches the mapped name.
     * <p>
     * The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, as well as direct equality. Can be
     * overridden in subclasses.
     *
     * @param beanName   the bean name to check
     * @param mappedName the name in the configured list of names
     * @return if the names match
     * @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
     */
    protected boolean isMatch(String beanName, String mappedName) {
        return PatternMatchUtils.simpleMatch(mappedName, beanName);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.notNull(annotations, "annotations cannot be null");
        annotations.forEach(annotation -> {
            String[] beanNames = context.getBeanNamesForAnnotation(annotation);
            Collections.addAll(this.beanNames, beanNames);
        });
    }

}
